<?php

class BoardDAO
{
	/* 
	 * The number of messages per page
	 */
	public static $PageSize = 50;
	
	/*
	 * Posts a message to the board
	 * @param $Text the text that is posted
	 * @param $Path the path to the message that this message is a reply to
	 * 			 	ie. '14/37/159' where 14, 37 and 159 are posts in the path
	 * @return $ID	the id to the post that is created, or 0 when creation failed. 
	 */
	public static function Post( $text, $path = '', $imageURL = '', $thumbURL = '')
	{
		// bump all messages in path
		$ids = explode('/', $path);
		foreach($ids as $id)
		{
			if($id > 0)
				self::Bump($id);
		}
		
		$message = R::dispense('message');
		$message->Text = $text;
		$message->Created = date( 'Y-m-d H:i:s', mktime() );
		$message->Score = 0;
		$message->Path = $path; 
		$message->ImageURL = $imageURL; 
		$message->ThumbURL = $thumbURL; 
		$id = R::store($message);
		return $id;
	}
	
	/*
	 * Increases the score of a message by one
	 * @param $ID the id of the message
	 */
	public static function Bump( $id )
	{
		r::exec('update message set score=score+1 where id=?', array( $id ));
	}
	
	/*
	 * Decreases the score of a message by one
	 * @param $ID the id of the message
	 */
	public static function Sage( $id )
	{
		r::exec('update message set score=score-1 where id=?', array( $id ));
	}
	
	/*
	 * Returns a list with the messages for a page
	 */
	public static function GetMessages( $path = '', $page = 1, $showFullPath = false, $orderByDate = false, $descending = true )
	{
		$start = ($page-1) * self::$PageSize;
		// build query and params
		$query = 'select * from message ';
		$values = array();
		// full path or not
		if($showFullPath)
		{
			$query .= 'where path LIKE ? ';
			$values[] = $path . '%';
		}
		else 
		{
			$query .= 'where path=? ';
			$values[] = $path;
		}
		// order by date or score
		if($orderByDate)
			$query .= 'order by created ';
		else
			$query .= 'order by score ';
		// ascending or descending
		if($descending)
			$query .= 'desc ';
		else
			$query .= 'asc ';
		$query .= 'limit ?, ?';
		$values[] = $start;
		$values[] = self::$PageSize;
		$messagesData = R::getAll($query, $values);
		return $messagesData;
	}
	
	/*
	 * Returns a message, or null if not found
	 */
	public static function GetMessage( $id )
	{
		$messageData = R::getRow('select * from message where id=?', array($id));
		return $messageData;
	}
	
	public function DeleteOldMessages()
	{
		/*
		 * get a datetime to work with
		 * 
		 * get all messages that comply to:
		 * - older than 5 minutes
		 * - score < 1
		 * delete the images from the messages
		 * delete the messages
		 * 
		 * get all messages that comply to:
		 * - not in top 1000 best messages
		 * do score = score - hours since last time bumped ^2 
		 */
	} 
}